package com.nit.netty.bean.aware;

import com.nit.netty.annotation.NettyService;
import com.nit.netty.worker.ServerWorker;
import com.nit.netty.zookeeper.registry.ServiceRegistry;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Author: whb
 * @Description:
 * @CreateTime: 2020/8/21 13:49
 */
public class NettyServerApplicationContextAware implements ApplicationContextAware, InitializingBean {

    private static final Logger logger = Logger.getLogger(NettyServerApplicationContextAware.class.getName());
    private Map<String, Object> serviceMap = new HashMap<>();
    ServerWorker runner;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        String address = applicationContext.getEnvironment().getProperty("remoteAddress");
        String zkAddress = applicationContext.getEnvironment().getProperty("zookeeper.address");
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(NettyService.class);
        for (Object serviceBean : beans.values()) {

            Class<?> clazz = serviceBean.getClass();

            Class<?>[] interfaces = clazz.getInterfaces();

            for (Class<?> inter : interfaces) {
                String interfaceSimpleName = inter.getSimpleName();
                String interfaceName = inter.getName();
                // 这里注册入zookeeper
                ServiceRegistry serviceRegistry = new ServiceRegistry(zkAddress);
                serviceRegistry.register(interfaceSimpleName, address);
                serviceMap.put(interfaceName, serviceBean);
            }
        }
        logger.info("已加载全部服务接口");
        runner = new ServerWorker(address, serviceMap);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        runner.open();
    }
}
